//
//  MyMessageViewController.m
//  BusinessApp
//
//  Created by CccDaxIN on 2016/10/12.
//  Copyright © 2016年 macox. All rights reserved.
//

#import "MyMessageViewController.h"
#import "MyMessageTableViewCell.h"
#import "MyMessageModel.h"
#import "UIView+ST.h"

@interface MyMessageViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    MyMessageTableViewCell *myCell;
    NSInteger pageNumber;//
    NSString *recordRefresh;
}
@property (nonatomic,strong)UITableView *myTableView;
@property (nonatomic, strong) NSMutableArray *messageArray;
@property (nonatomic, strong)NSMutableArray *pagingArray;
@property (nonatomic,assign)NSInteger MaxId;
@end

@implementation MyMessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"消息";
    pageNumber = 1;
    recordRefresh = @"data";
    self.view.backgroundColor = [UIColor whiteColor];
    [self myMessageDataRequestLoad];

    [self createMyMessageTableView];
    /*
     *返回
     */
    UIImage *myMessageBackImage = [UIImage imageNamed:@"左箭头"];
    myMessageBackImage = [myMessageBackImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:myMessageBackImage style:UIBarButtonItemStylePlain target:self action:@selector(myMessageBackAction)];

    // Do any additional setup after loading the view.
}
- (void)myMessageBackAction{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];}
#pragma mark --  创建tableview
- (void)createMyMessageTableView{
    _myTableView =[[UITableView alloc]initWithFrame:CGRectMake(0,0, kScrernWidth,kScrernHeight+48) style:UITableViewStylePlain];
    _myTableView.showsVerticalScrollIndicator = FALSE;
    _myTableView.delegate=self;
    _myTableView.dataSource=self;
    _myTableView.backgroundColor = [UIColor colorWithHue:0.00 saturation:0.00 brightness:0.94 alpha:1.00];
    _myTableView.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:_myTableView];
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _messageArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyMessageModel *personalHomepageModel = _messageArray[indexPath.row];
    NSString * titleString = personalHomepageModel.MessageContent;
    CGSize sizeToFit_Title;
    sizeToFit_Title = [titleString boundingRectWithSize:CGSizeMake(kScrernWidth-60, 100) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:15]} context:nil].size;
    return sizeToFit_Title.height+50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"MyMessage";
    myCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (myCell == nil) {
        myCell = [[[NSBundle mainBundle] loadNibNamed:@"MyMessageTableViewCell" owner:nil options:nil] firstObject];
    }
    [myCell.contentView setBackgroundColor: [UIColor whiteColor]];
    myCell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    MyMessageModel *myMessageModel  = [_messageArray objectAtIndex:indexPath.row];
    myCell.myMessageText.text = myMessageModel.MessageContent;
    myCell.dateTimeLabel.text = myMessageModel.SendTime;
    if (myMessageModel.IsRead == 0) {
        myCell.unreadImage.image = [UIImage imageNamed:@"删除图片"];
    }else{
        myCell.unreadImage.image = [UIImage imageNamed:@""];
    }
    return myCell;
}

#pragma mark -- 刷新加载数据
- (void)example21:(NSString *)MaID{
    __unsafe_unretained __typeof(self) weakSelf = self;
    NSLog(@"查询");
    //        weakSelf.storeListTableView.mj_header.hidden = NO;
    // 下拉刷新
    weakSelf.myTableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        //        pageNumber = 1;
//        [self myMessageDataRequestLoad];
        
        [weakSelf.myTableView reloadData];
        // 结束刷新
        [weakSelf.myTableView.mj_header endRefreshing];
        
    }];
    //    [weakSelf.sellCenterTableV.mj_header beginRefreshing];
    // 上拉刷新
    weakSelf.myTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        pageNumber ++;

        [self myMessageDataRequestLoad:[NSString stringWithFormat:@"%ld", (long)pageNumber ]:MaID];
        
        [weakSelf.myTableView reloadData];
        // 结束刷新
        [weakSelf.myTableView.mj_footer endRefreshing];
        
    }];
    // 默认先隐藏footer
    weakSelf.myTableView.mj_footer.hidden = NO;
}

#pragma mark -- 请求下一页的数据
- (void)myMessageDataRequestLoad:(NSString *)pageNumber:(NSString *)MaxId{
    _pagingArray = [NSMutableArray array];
    [GDJHttpTool get:MyMessageListTop params:@{@"ShouJiHao":GETPHONE,@"Duuid":GETUUID,@"Token":GETTOKEN,@"Index":pageNumber,@"MaxId":MaxId} success:^(id responseObj) {
        NSLog(@"你知道我在等你么 %@",responseObj);
        [SVProgressHUD showWithStatus:@"正在加载"];
//        [_messageArray removeAllObjects];
        //查看错误码
        NSInteger err = [[responseObj valueForKey:@"Err"]integerValue];
        NSLog(@"争取吧%ld",(long) err);
        if (err == 0) {
            [SVProgressHUD dismiss];
            _pagingArray =   [MyMessageModel mj_objectArrayWithKeyValuesArray:[responseObj objectForKey:@"MessageLogs"]];
            if (_pagingArray.count != 0) {
                [_messageArray addObjectsFromArray:_pagingArray];
                MyMessageModel * model = _messageArray[0];
                [self.myTableView reloadData];
                [self example21:[NSString stringWithFormat:@"%d",model.Id]];
            }
        }else{
            NSLog(@"%@",responseObj[@"ErrMsg"]);
            [SVProgressHUD showErrorWithStatus:responseObj[@"ErrMsg"]];
            return;
        }
        [_myTableView reloadData];
    }failure:^(NSError *error) {
        NSLog(@"error:%@",error);
    }];
}
#pragma mark -- 我de消息列表上划
- (void)myMessageDataRequestLoad
{
    [GDJHttpTool get:MyMessageListTop params:@{@"ShouJiHao":GETPHONE,@"Duuid":GETUUID,@"Token":GETTOKEN,@"Index":@"1",@"MaxId":@"0"} success:^(id responseObj) {
        NSLog(@"你知道我在等你么 %@",responseObj);
        [SVProgressHUD showWithStatus:@"正在加载"];
        //查看错误码
        NSInteger err = [[responseObj valueForKey:@"Err"]integerValue];
        NSLog(@"争取吧%ld",(long) err);
        if (err == 0) {
            [SVProgressHUD dismiss];
             _messageArray =   [MyMessageModel mj_objectArrayWithKeyValuesArray:[responseObj objectForKey:@"MessageLogs"]];
            if (_messageArray.count != 0) {
                MyMessageModel * model = _messageArray[0];
                [self example21:[NSString stringWithFormat:@"%d",model.Id]];
            }
        }else{
            NSLog(@"%@",responseObj[@"ErrMsg"]);
            [SVProgressHUD showErrorWithStatus:responseObj[@"ErrMsg"]];
            return;
        }
        [_myTableView reloadData];
    }failure:^(NSError *error) {
        NSLog(@"error:%@",error);
    }];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    recordRefresh = @"did";
    MyMessageModel * model = _messageArray[indexPath.row];
    NSLog(@"蓝瘦香菇%d",model.Id);
    NSString *stringID = [NSString stringWithFormat:@"%d",model.Id];
    [GDJHttpTool get:MyMessageRead params:@{@"ShouJiHao":GETPHONE,@"Duuid":GETUUID,@"Token":GETTOKEN,@"Ids":stringID} success:^(id responseObj) {
        NSLog(@"我懂了 %@",responseObj);
        
        //查看错误码
        NSInteger err = [[responseObj valueForKey:@"Err"]integerValue];
        NSLog(@"争取吧%ld",(long) err);
        if (err == 0) {
            for (MyMessageModel * model in _messageArray) {
                NSString *string = [NSString stringWithFormat:@"%d",model.Id];
                if ([string isEqualToString: stringID]) {
                    model.IsRead = 1;
                }
            }
            [self.myTableView reloadData];
        }else{
            [SVProgressHUD showErrorWithStatus:@"数据加载失败" ];
        }
    }failure:^(NSError *error) {
        
    }];
}
#pragma mark -- 更新消息已读状态
- (void)messageReadStateDataRequest{
    }

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
